package com.groupbuying.orderconsumer.service.impl;

import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.groupbuying.orderconsumer.constant.CommodityOrderItemEnumConstants;
import com.groupbuying.orderconsumer.constant.CommodityOrderMainEnumConstants;
import com.groupbuying.orderconsumer.dao.CommodityOrderItemDao;
import com.groupbuying.orderconsumer.dao.CommodityOrderMainDao;
import com.groupbuying.orderconsumer.domain.CommodityOrderItemDO;
import com.groupbuying.orderconsumer.domain.CommodityOrderMainDO;
import com.groupbuying.orderconsumer.service.CommodityOrderUshopService;
import com.groupbuying.orderconsumer.utils.apiresult.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 优店商品订单业务实现类
 *
 * @author m
 */
@Service
public class CommodityOrderUshopServiceImpl implements CommodityOrderUshopService {
    public static final Logger LOGGER = LoggerFactory.getLogger(CommodityOrderUshopServiceImpl.class);

    @Autowired
    private CommodityOrderMainDao commodityOrderMainDao;
    @Autowired
    private CommodityOrderItemDao commodityOrderItemDao;

    /**
     * 修改商品主订单状态
     * @param param map参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult changeCommodityMainOrderStateService(Map<String, ?> param) {
        LOGGER.info("打印：消费者，修改商品主订单状态，参数：{}",JSON.toJSONString(param));
        //判断参数
        if (param == null) {
            LOGGER.error("商品订单修改状态修改，参数为空");
            return ApiResult.paramIsNull();
        }

        String orderId = param.get("id")==null?null:param.get("id").toString();
        if (org.apache.commons.lang3.StringUtils.isEmpty(orderId)) {
            LOGGER.error("商品订单修改状态修改，商品订单id为空");
            return ApiResult.paramIsNull();
        }

        String orderState = param.get("orderState")==null?null:param.get("orderState").toString();
        if (StringUtils.isEmpty(orderState)) {
            LOGGER.error("商品订单修改状态修改，商品订单状态为空");
            return ApiResult.paramIsNull();
        }

        //查询主订单
        CommodityOrderMainDO mainDO = commodityOrderMainDao.get(orderId);

        if (mainDO == null){
            LOGGER.error("修改商品订单状态，没有查询到主订单,商品订单id{}",orderId);
            return ApiResult.failure();
        }

        String mainState = mainDO.getOrderState().toString();

        Map<String,Object> mParam = new HashMap<>();
        Map<String,Object> iParam = new HashMap<>();
        //1. 待发货 主订单不是待发、是未支付、已关闭才可以修改
        if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY.equals(orderState)){
            //商品最终金额
            BigDecimal payAmount = new BigDecimal(param.get("payAmount").toString());

            if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY.equals(mainState)){
                LOGGER.info("修改商品主订单状态，重复提交，订单状态已是待发货状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_UNPAY.equals(mainState)
                    || CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED.equals(mainState)){
                mParam.put("id",orderId);   //订单id
                mParam.put("orderState",CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY);   //订单状态
                mParam.put("gmtModify",new Date());   //订单修改时间
                mParam.put("paymentTime",new Date());   //支付时间
                mParam.put("payAmount",payAmount);   //实际支付金额
                //金额修改
                //修改主订单
                commodityOrderMainDao.updateById(mParam);

                iParam.put("orderId",mainDO.getId());  //订单id
                iParam.put("updateTime",new Date());  //更新时间
                iParam.put("paymentTime",new Date());  //支付时间
                iParam.put("presentTotal",payAmount);   //实际支付金额
                //金额修改
                iParam.put("status", CommodityOrderItemEnumConstants.ENUM_STATUS_WAIT_FOR_DELIVERY);
                //修改子订单状态
                commodityOrderItemDao.updateByOrderId(iParam);
                LOGGER.info("修改商品主订单状态，待发货状态修改成功，主订单id：{}",orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品主订单状态，待发货状态修改有误，主订单id：{}",orderId);
            return ApiResult.failure();
        }

        //2. 关闭状态 不是关闭状态、是待支付状态可以修改
        if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED.equals(orderState)){
            if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_WAIT_FOR_DELIVERY.equals(mainState)){
                LOGGER.info("修改商品主订单状态，已经是待发货状态，订单状态已是关闭状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED.equals(mainState)){
                LOGGER.info("修改商品主订单状态，重复修改状态，订单状态已是关闭状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_UNPAY.equals(mainState)){

                mParam.put("id",orderId);   //订单id
                mParam.put("orderState",CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_CLOSED);   //订单状态
                mParam.put("gmtModify",new Date());   //订单修改时间
                //修改主订单
                commodityOrderMainDao.updateById(mParam);

                LOGGER.info("修改商品主订单状态，关闭状态修改成功，主订单id：{}",orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品主订单状态，关闭状态修改有误，主订单id：{}",orderId);
            return ApiResult.failure();
        }

        LOGGER.error("修改商品订单状态，当前状态有误，子订单id：{},状态：{}",orderId,orderState);
        return ApiResult.failure();
    }

    /**
     * 修改商品子订单状态
     * @param param map参数
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApiResult changeCommodityItemOrderStateService(Map<String, ?> param) {

        LOGGER.info("打印：修改商品子订单状态，参数：{}",JSON.toJSONString(param));
        //商品订单状态
        String orderState = param.get("orderState").toString();
        //商品主订单id
        String orderId = param.get("orderId").toString();

        // 查询子订单信息
        CommodityOrderItemDO itemDO = commodityOrderItemDao.get(orderId);

        if (itemDO == null){
            LOGGER.error("修改商品子订单状态，没有查询到子订单,商品订单id{}",orderId);
            return ApiResult.failure();
        }

        String itemState = itemDO.getStatus().toString();

        Map<String,Object> iUpdateParam = new HashMap<>();
        Map<String,Object> iSerchParam = new HashMap<>();
        Map<String,Object> mParam = new HashMap<>();
        //1.（主订单与子订单）待发 已发 已收
        //1.1 已发货 不是已发货、是待发货才可修改
//        if (CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY.equals(itemState)){
//            if (!CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY.equals(itemState)
//                    && CommodityOrderItemEnumConstants.ENUM_STATUS_WAIT_FOR_DELIVERY.equals(itemState)){
//                iUpdateParam.put("id",itemDO.getId());  //子订单id
//                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY);    //状态
//
//                //修改子订单状态
//                commodityOrderItemDao.updateById(iUpdateParam);
//
//                //查询状态数
//                iSerchParam.put("id",orderId);
//                iSerchParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY);
//                iSerchParam.put("is_delete",CommodityOrderItemEnumConstants.ENUM_ISDELETE_UNDEL);
//                int count = commodityOrderItemDao.findOtherStateCount(iSerchParam);
//
//                if (count>0){
//                    mParam.put("id",itemDO.getOrderId());
//                    mParam.put("orderState",CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_DELIVERY);
//                    //修改主订单
//                    commodityOrderMainDao.updateById(mParam);
//                    LOGGER.info("修改商品子订单状态，主订单，已发货状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
//                }
//
//                LOGGER.info("修改商品子订单状态,已发货状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
//                return ApiResult.success();
//            }
//            LOGGER.info("修改商品订单状态，已发货状态修改有误，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
//            return ApiResult.failure();
//        }

        //1.2 已收货(并修改主订单已完成) 不是已收货、是已发货、待发货才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(orderState)){
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(itemState)){
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是已收货状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_DELIVERY.equals(itemState)
                    || CommodityOrderItemEnumConstants.ENUM_STATUS_WAIT_FOR_DELIVERY.equals(itemState)){
                iUpdateParam.put("id",itemDO.getId());
                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED);
                iUpdateParam.put("receiverTime",new Date());  //收货时间
                iUpdateParam.put("updateTime",new Date());   //订单修改时间

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);

                //查询状态数
                iSerchParam.put("orderId",itemDO.getOrderId());
                iSerchParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED);
                iSerchParam.put("isDelete",CommodityOrderItemEnumConstants.ENUM_ISDELETE_UNDEL);
                int count = commodityOrderItemDao.findOtherStateCount(iSerchParam);

                if (count<=0){
                    mParam.put("id",itemDO.getOrderId());
                    mParam.put("orderState",CommodityOrderMainEnumConstants.ENUM_ORDERSTATE_FINISHED);
                    mParam.put("receiverTime",new Date());
                    mParam.put("gmtModify",new Date());   //订单修改时间
                    //修改主订单
                    commodityOrderMainDao.updateById(mParam);
                    LOGGER.info("修改商品子订单状态，主订单，已收货状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
                }
                LOGGER.info("修改商品子订单状态，已收货状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品子订单状态，已收货状态修改有误，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
            return ApiResult.failure();
        }

        //2.（体现在子订单）退货 退货中 已退货 换货 换货中 换货成功
        //2.1 退款中 不是退款中、是已收货才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING.equals(orderState)){
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING.equals(itemState)){
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是退款中状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(itemState)){
                //修改子订单状态
                iUpdateParam.put("id",itemDO.getId());
                iUpdateParam.put("updateTime",new Date());   //订单修改时间
                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，退款中状态修改成功，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
                return ApiResult.success();
            }
            LOGGER.info("修改商品子订单状态，退款中状态修改有误，主订单id：{}，子订单id：{}",itemDO.getOrderId(),orderId);
            return ApiResult.failure();
        }
        //2.2 已退货 不是已退货、是退款中才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNED.equals(orderState)){
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNED.equals(itemState)){
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是已退货状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if(CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNING.equals(itemState)){

                iUpdateParam.put("id",itemDO.getId());
                iUpdateParam.put("updateTime",new Date());   //订单修改时间
                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_RETURNED);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，已退货状态修改成功，子订单id：{}",orderId);
                return ApiResult.success();
            }
            LOGGER.info("修改商品子订单状态，已退货状态修改有误，子订单id：{}",orderId);
            return ApiResult.failure();
        }
        //2.3 换货中 不是换货中、是已收货才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING.equals(orderState)){
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING.equals(itemState)){
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是换货中状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_RECEIVED.equals(itemState)){
                iUpdateParam.put("id",itemDO.getId());
                iUpdateParam.put("updateTime",new Date());   //订单修改时间
                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，换货中状态修改成功，子订单id：{}",orderId);
                return ApiResult.success();
            }
            LOGGER.info("修改商品子订单状态，换货中状态修改有误，子订单id：{}",orderId);
            return ApiResult.failure();
        }
        //2.4 换货成功 不是换货成功、是换货中才可修改
        if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGED.equals(orderState)){
            if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGED.equals(itemState)){
                LOGGER.info("修改商品子订单状态，重复修改状态，订单状态已是换货成功状态，主订单id：{}",orderId);
                return ApiResult.success();
            } else if (CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGING.equals(itemState)){
                iUpdateParam.put("id",itemDO.getId());
                iUpdateParam.put("updateTime",new Date());   //订单修改时间
                iUpdateParam.put("status",CommodityOrderItemEnumConstants.ENUM_STATUS_EXCHANGED);

                //修改子订单状态
                commodityOrderItemDao.updateById(iUpdateParam);
                LOGGER.info("修改商品子订单状态，换货成功状态修改成功，子订单id：{}",orderId);
                return ApiResult.success();
            }
            LOGGER.error("修改商品子订单状态，换货成功状态修改有误，子订单id：{}",orderId);
            return ApiResult.failure();
        }

        LOGGER.error("修改商品子订单状态，当前状态有误，子订单id：{},状态：{}",orderId,orderState);
        return ApiResult.failure();
    }
}

